package com.jack.lib.net.interceptor

import com.blankj.utilcode.util.EncryptUtils
import com.jack.lib.core.ext.toJson
import com.jack.lib.core.utils.JLog
import com.jack.lib.net.INet
import com.jack.lib.net.JNetManager
import com.jack.lib.net.cache.NetCache
import com.jack.lib.net.throwable.RepeatException
import okhttp3.*
import okio.Buffer

/**
 * author : chong.huang
 * create : 2021/12/30
 * desc   :
 */
class JHeaderInterceptor(private val inet: INet) : Interceptor {


    override fun intercept(chain: Interceptor.Chain): Response {

        val original = chain.request()
        val requestBuilder = original.newBuilder()
        requestBuilder.addHeader("Content-Type", "application/json; charset=utf-8")
        val headers = inet.headers(original.url.toString()).filter { !it.value.isNullOrEmpty() }
        headers.forEach {
            if (original.header(it.key) == null) {
                requestBuilder.addHeader(it.key, it.value!!)
            }
        }
        JLog.d(JNetManager.TAG, "headers: " + headers.toJson())
        val request = requestBuilder.build()

        //val encryptMD5ToString = EncryptUtils.encryptMD5ToString(request.toString())
        //if (NetCache.contains(encryptMD5ToString)) {
        //    throw RepeatException("${request.url} 接口重复请求")
        //}
        NetCache.put(EncryptUtils.encryptMD5ToString(request.toString()))

        when (val body = request.body) {
            is FormBody ->  checkAndPrint(request, getBodyBuilder(body))
            else -> checkAndPrint(request, getBodyBuilder(body))
        }
        return chain.proceed(request)
    }

    private fun getBodyBuilder(body: FormBody?): java.lang.StringBuilder {
        return StringBuilder().apply {
            val size = body?.size?: return this
            append("{")
            for(i in 0 until size) {
                val name = body.name(i)
                val value = body.value(i)
                append(name)
                append(":")
                append(value)
                append(", ")
            }
            if (contains(", ")) {
                deleteCharAt(lastIndex)
                deleteCharAt(lastIndex)
            }
            append("}")
        }
    }

    private fun getBodyBuilder(request: RequestBody?): java.lang.StringBuilder {
        return StringBuilder().apply {
            val buffer = Buffer()
            request?.writeTo(buffer)?: return this
            val body = buffer.readUtf8()
            append(body)
        }
    }

    private fun checkAndPrint(request: Request, builder: StringBuilder) {
        JLog.d(JNetManager.TAG, "body:   $builder")
    }
}